package cl.blueprintsit.utils.bdd;

import org.apache.log4j.Logger;

import java.sql.*;

public class Closer {

    private static Logger logger = Logger.getLogger(Closer.class);

    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                logger.error("The resultset could not be closed.");
            }
        }

        /* The connection is closed */
        close(preparedStatement, connection);
    }

    public static void close(CallableStatement callableStatement, Connection connection) {
        if (callableStatement != null) {
            try {
                callableStatement.close();
            } catch (SQLException e) {
                logger.error("The callable statement could not be closed: " + e.getMessage());
            }
        }

        /* The connection is closed */
        close(connection);
    }

    /**
     * This method is responsible for closing the connection.
     *
     * @param connection The connection that is to be closed.
     */
    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("The resultset could not be closed.");
            }
        }

    }

    public static void close(PreparedStatement preparedStatement, Connection connection) {

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                logger.error("The resultset could not be closed.");
            }

        }

        close(connection);
    }
}
